﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;

namespace NapThe
{
    public class ServiceController : Controller
    {
        public static string x = "";
        public static bool sent = false;

        public static bool enoughMoney()
        {
            bool enough = false;
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            string myString = "";

            if (storage.FileExists("Money.txt"))
            {
                int currMoney = 0;
                IsolatedStorageFileStream fileStream = storage.OpenFile("Money.txt", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    myString = reader.ReadLine();
                    myString = removeFirst(myString);
                    myString = NapTheDienThoaiController.Decrypt(myString,
                        "bkth83sh48jd92pq94hn81c0b47j32m6",
                        "5t93v31hg5yg9hs");
                    currMoney = Int32.Parse(parse(myString));
                    reader.Close();
                    fileStream.Close();
                    if (currMoney >= 1500)
                    {
                        enough = true;
                        currMoney -= 1500;
                        myString = "" + currMoney;

                        FileStream stream = storage.OpenFile("Money.txt", FileMode.Create); // Open a file in Create mode
                        BinaryWriter writer = new BinaryWriter(stream);
                        myString = NapTheDienThoaiController.Encrypt(myString,
                                    "bkth83sh48jd92pq94hn81c0b47j32m6",
                                    "5t93v31hg5yg9hs");
                        writer.Write(myString);
                        writer.Close();
                        stream.Close();
                    }
                }

                //MessageBox.Show(myString);

                storage.Dispose();
            }

            return enough;
        }

        private static string removeFirst(string t)
        {
            return t.Substring(1);
        }

        public static string parse(string x)
        {
            string t = "";
            char[] array = x.ToCharArray();
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] >= '0' && array[i] <= '9')
                {
                    t = t + array[i];
                }
            }

            return t;
        }

        private static void getMoney()
        {
            bool found = false;
            char[] t = x.ToCharArray();
            int i = x.Length - 1;
            while (i >= 0 && !found)
            {
                if (t[i] == '|')
                {
                    found = true;
                }
                else
                {
                    i--;
                }
            }

            string r = x.Substring(i);
            x = parse(r);
            return;
        }

        public static bool isFinish(string t)
        {
            t = t.Trim();
            x = "";
            bool found = true;
            int i = t.Length - 1;
            char[] c = t.ToCharArray();
            while (found && i >= 0)
            {
                if (c[i] >= '0' && c[i] <= '9')
                {
                    x = c[i] + x;
                    i--;
                }
                else
                {
                    found = false;
                }
            }
            if (!found && i < t.Length - 1)
            {
                found = true;
            }
            else
            {
                found = false;
            }
            return found;
        }

        public static ServiceController get(string t)
        {
            t = t.Trim();
            if (isFinish(t))
            {
                x = t;
                getMoney();
                x = getMessage(t);
                return new Service01();
            }
            else
            {
                x = getMessage(t);
                return new Service02();
            }
        }

        public static string getMessage(string t)
        {
            string result = "";
            char[] c = t.ToCharArray();
            int i = 0;
            bool found = false;
            while (!found && i < t.Length - 1)
            {
                if (c[i] != '|')
                {
                    i++;
                }
                else
                {
                    found = true;
                }
            }
            i++;

            while (found && i <= t.Length - 1)
            {
                if (c[i] != '|')
                {
                    result = result + c[i];
                    i++;
                }
                else
                {
                    found = false;
                }
            }
            return result;
        }

        public static ServiceController getNapThe(string t)
        {
            t = t.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
            if (t.Contains("<error>"))
            {
                //x = "Access Time Error";
                x = removeAllTags(t);
                return new ServiceP0();
            }
            if (t.Contains("Coupon is not valid"))
            {
                x = "Coupon is not valid";
                return new ServiceP1();
            }
            t = t.Trim();
            t = t.Replace("<value>", "}");
            t = t.Replace("</value>", "}");
            x = t;
            //t = t.Substring(4);
            //var entry = XDocument.Parse(t);
            //MessageBox.Show(entry.LastNode.ToString());
            //x = (string)entry.Element("data");
            getTheCao();
            //x = (string)entry.Element("description");
            //x = (string)entry.Element("discount");
            //x = (string)entry.Element("value");

            //x = "" + (int)entry.Element("value");
            return new ServiceP2();
        }


        private static string removeAllTags(string t)
        {
            string y = "";
            y = t.Replace("<data>", " ");
            y = y.Replace("</data>", " ");
            y = y.Replace("<error>", " ");
            y = y.Replace("</error>", " ");
            //y = y.Replace("\\n", " ");
            var sb = new StringBuilder(y.Length);

            foreach (char i in y)
                if (i != '\n' && i != '\r' && i != '\t')
                    sb.Append(i);

            y = sb.ToString();


            y = y.Trim();
            return y;
        }

        private static void getTheCao()
        {
            string t = "";
            int i = 0;
            char[] x1 = x.ToCharArray();
            while (i < x.Length)
            {
                if (x1[i] == '}')
                {
                    break;
                }
                i++;
            }
            i++;
            while (i < x.Length)
            {
                if (x1[i] == '}')
                {
                    break;
                }
                else
                {
                    t = t + x1[i];
                    i++;
                }
            }
            x = t;
        }

        public virtual string show()
        {
            return "";
        }

        public static int getXu(int money)
        {
            int xu = 0;
            if (money <= 10000 && money > 0)
            {
                xu = (int)(21 * money / 10);
                return xu;
            }
            if (money <= 20000)
            {
                xu = (int)(22 * money / 10);
                return xu;
            }
            if (money <= 50000)
            {
                xu = (int)(23 * money / 10);
                return xu;
            }
            if (money <= 100000)
            {
                xu = (int)(24 * money / 10);
                return xu;
            }
            if (money <= 200000)
            {
                xu = (int)(25 * money / 10);
                return xu;
            }

            xu = (int)(26 * money / 10);

            return xu;
        }

        public virtual bool enableProcess(string fileName1, string fileName2)
        {
            if (isThirdTime(fileName1))
            {
                if (isWaiting(fileName1, fileName2))
                {
                    return false;
                }
            }

            return true;
        }

        public bool isThirdTime(string fileName1)
        {
            bool isThirdTime = false;
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            string myString = "Zero";
            string number = "Zero";
            //number = NapTheDienThoaiController
            if (storage.FileExists(fileName1))
            {
                IsolatedStorageFileStream fileStream = storage.OpenFile(fileName1, FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    myString = reader.ReadLine();
                    myString = myString.Substring(1);
                    myString = NapTheDienThoaiController.Decrypt(myString,
                                    "uml20bv117granmt43twji89bg32pl09",
                                    "olc57mgfd5jnibf4uony8");

                    reader.Close();
                    reader.Dispose();
                }

                fileStream.Close();
                fileStream.Dispose();
            }

            if ("Third".Equals(myString))
            {
                storage.Dispose();
                return true;
            }

            if (!myString.Equals(number))
            {
                if ("Second".Equals(myString) && sent)
                {
                    myString = "Third";
                }
                else
                {
                    if ("First".Equals(myString) && sent)
                    {
                        myString = "Second";
                    }
                }
            }
            else
            {
                if (sent)
                {
                    myString = "First";
                }
            }

            if (sent)
            {
                FileStream stream = storage.OpenFile(fileName1, FileMode.Create); // Open a file in Create mode
                BinaryWriter writer = new BinaryWriter(stream);
                myString = NapTheDienThoaiController.Encrypt(myString,
                            "uml20bv117granmt43twji89bg32pl09",
                            "olc57mgfd5jnibf4uony8");
                writer.Write(myString);
                writer.Close();
                writer.Dispose();
                stream.Close();
                stream.Dispose();
            }

            storage.Dispose();
            return isThirdTime;
        }



        public bool isWaiting(string fileName1, string fileName2)
        {
            bool stillWaiting = true;
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            if (storage.FileExists(fileName2))
            {
                IsolatedStorageFileStream fileStream = storage.OpenFile(fileName2,
                    FileMode.Open, FileAccess.Read);
                using (BinaryReader reader = new BinaryReader(fileStream))
                {
                    int y = reader.ReadInt32();
                    int m = reader.ReadInt32();
                    int d = reader.ReadInt32();
                    int h = reader.ReadInt32();
                    int mi = reader.ReadInt32();
                    int sec = reader.ReadInt32();
                    //myString = myString.Substring(1);
                    DateTime d1 = new DateTime(y, m, d, h, mi, sec);
                    DateTime now = DateTime.Now;
                    System.TimeSpan diff = now.Subtract(d1);
                    if (diff.Minutes >= 30)
                    {
                        stillWaiting = false;
                    }
                    else
                    {
                        x = "Bạn đã nhập sai 3 lần. Xin hãy đợi thêm " +
                                    (30 - diff.Minutes) + " phút nữa!";
                    }
                    reader.Close();
                    reader.Dispose();
                }

                fileStream.Close();
                fileStream.Dispose();

                if (!stillWaiting)
                {
                    storage.DeleteFile(fileName2);
                    if (storage.FileExists(fileName1))
                    {
                        storage.DeleteFile(fileName1);
                    }
                }
            }
            else
            {
                x = "Bạn đã nhập sai 3 lần. Xin hãy đợi đủ 30 phút nữa!";
                IsolatedStorageFileStream f = storage.CreateFile(fileName2);
                using (BinaryWriter writer = new BinaryWriter(f))
                {
                    //myString = (DateTimeOffset)storage.GetCreationTime
                    DateTime d1 = DateTime.Now;
                    int y = d1.Year;
                    int m = d1.Month;
                    int d = d1.Day;
                    int h = d1.Hour;
                    int mi = d1.Minute;
                    int sec = d1.Second;
                    writer.Write(y);
                    writer.Write(m);
                    writer.Write(d);
                    writer.Write(h);
                    writer.Write(mi);
                    writer.Write(sec);
                    writer.Close();
                    writer.Dispose();
                }

                f.Close();
                f.Dispose();
            }

            storage.Dispose();
            return stillWaiting;
        }
    }

    public class ServiceP0 : ServiceController
    {
        public override string show()
        {
            return x;
        }
    }

    public class ServiceP1 : ServiceController
    {
        public override string show()
        {
            return x;
        }
    }

    public class ServiceP2 : ServiceController
    {
        public override string show()
        {
            return "Kiểm tra thành công";
        }
    }

    public class Service00 : ServiceController
    {
        public override string show()
        {
            return "Mã số nạp tiền không tồn tại hoặc đã được sử dụng";
        }
    }

    public class Service01 : ServiceController
    {
        public override string show()
        {
            //getMoney();
            return x;
        }

        public override bool enableProcess(string fileName1, string fileName2)
        {
            return true;
            //return base.enableProcess();
        }

    }

    public class Service02 : ServiceController
    {
        public override string show()
        {
            return x;
        }
    }

}
